// 官方文档：https://vue3js.cn/router4/guide/#html

// 引入vue-router对象
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

// 引入路由守卫方法
import beforeEach from './modules/beforeEach'

import nprogress from 'nprogress' // @types/nprogress
import 'nprogress/nprogress.css'

nprogress.configure({
  easing: 'ease', // 动画方式
  speed: 300, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3 // 初始化时的最小百分比
})

function registerRoute () {
  const routerList: any = []
  /* webpack写法
  const modules = require.context('./', false, '/.router.ts$/')
  */
  const modules: any = import.meta.globEager('./*.router.ts')
  for (const val of Object.values(modules)) routerList.push(val.default)
  return routerList.flat()// 用于将嵌套的数组拉平 [1, 2, [3, 4]].flat()// [1, 2, 3, 4]
}

const routes: Array<RouteRecordRaw> = [
  ...registerRoute(),
  { // 404路由
    path: '/404',
    name: '404',
    component: () => import('../views/other/404.vue')
  },
  { // 后端管理系统路由组
    path: '/admin',
    name: 'admin',
    component: () => import('../views/admin/Index.vue')
  },
  {
    path: '/background',
    name: 'background',
    component: () => import('../views/other/background.vue')
  },
  {
    path: '/',
    name: 'home',
    component: () => import('../views/home/Index.vue')
  },
  {
    path: '/article',
    name: 'article',
    component: () => import('../views/article/Index.vue')
  },
  {
    path: '/article/:id',
    name: 'articleId',
    component: () => import('../views/article/_id.vue')
  },
  {
    path: '/history',
    name: 'history',
    component: () => import('../views/history/Index.vue')
  },
  {
    path: '/chat',
    name: 'chat',
    component: () => import('../views/chat/Index.vue')
  },
  {
    path: '/msg',
    name: 'msg',
    component: () => import('../views/msg/Index.vue')
  },
  {
    path: '/works',
    name: 'works',
    component: () => import('../views/works/Index.vue')
  },
  {
    path: '/link',
    name: 'link',
    component: () => import('../views/link/Index.vue')
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/about/Index.vue')
  },
  {
    path: '/tag/:id',
    name: 'tag',
    component: () => import('../views/tag/_id.vue')
  }
]

/**
 * 创建路由
 */
const router = createRouter({
  // hash模式：createWebHashHistory，
  // history模式：createWebHistory

  // history:createWebHashHistory("/#"),
  history: createWebHistory(import.meta.env.BASE_URL), // 路由模式
  routes // 路由规则
})

/**
 * 路由守卫
 */
router.beforeEach((guard) => {
  // 每次切换页面时，调用进度条
  nprogress.start()
  beforeEach.checkAuth(guard, router)
})

router.afterEach(() => {
  // 在即将进入新的页面组件前，关闭掉进度条
  nprogress.done()
})

/**
 * 路由错误回调
 */
router.onError((handler) => {
  console.log('error:', handler)
})

/**
 * 输出对象
 */
export default router
